package com.loanapp.server.sso.controller.login;


import com.loanapp.base.common.constants.AppConstant;
import com.loanapp.base.common.constants.BusinessConstant;
import com.loanapp.base.common.dto.ResponseDto;
import com.loanapp.base.common.exception.BizExceptionEnum;
import com.loanapp.base.common.exception.BusinessException;
import com.loanapp.base.common.utils.StringUtil;
import com.loanapp.base.controller.common.BaseController;
import com.loanapp.base.controller.support.HttpKit;
import com.loanapp.server.sso.constant.LoginValidate;
import com.loanapp.server.user.api.user.api.UserApi;
import com.loanapp.server.user.api.user.entity.User;
import com.loanapp.server.user.api.user.query.UserQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@CrossOrigin(origins = {"http://106.14.97.38","http://106.14.12.38"})
@RequestMapping(value = "main")
@Api(value = "登录控制器", description = "登录API")
@RestController
public class AppLoginController extends BaseController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    UserApi userApi;


    @ApiOperation(value = "账号密码登录", notes="",
            produces = "application/json; charset=utf-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
            @ApiImplicitParam(name = "pwd", value = "密码",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
    })
    @RequestMapping(value = "login",method = RequestMethod.GET)
    protected ResponseDto Login(@RequestParam(required = false) String phone,
                                @RequestParam(required = false) String pwd) throws BusinessException{
        ResponseDto result=ResponseDto.build(000,"成功");
        if(StringUtil.isEmpty(phone)||StringUtil.isEmpty(pwd)){
           throw new BusinessException(BizExceptionEnum.REQUEST_NULL);
        }
        UserQuery userQuery=new UserQuery();
        userQuery.setPhone(phone);
        User user=userApi.selectByQuery(userQuery);
        if(user==null){
           result.setMesg("账号不存在");
           return result;
        }
        else {
            if(!user.getPassword().equals(pwd)){
                    result.setMesg("密码错误");
            }
            else {
                //key 存入redis 并且返回响应
                String sso_user_key= StringUtil.getUUID();
                redisTemplate.opsForValue().set(sso_user_key,user,30,TimeUnit.MINUTES);
                HttpKit.addCookie(HttpKit.getResponse(),"sso_key",sso_user_key,3600);
                result.setData(sso_user_key);
            }
        }
        return result;
    }

    @ApiOperation(value = "修改密码", notes="",
            produces = "application/json; charset=utf-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token秘钥",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
            @ApiImplicitParam(name = "oldPwd", value = "旧密码",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
            @ApiImplicitParam(name = "newPwd", value = "新设置密码",
                    dataType = "int", paramType = "query", defaultValue="",required = true)
    })
    @CrossOrigin(origins ={"http://106.14.97.38","http://106.14.12.38"})
    @RequestMapping(value = "changePwd",method = RequestMethod.GET)
    @LoginValidate
    public ResponseDto changePwd(@RequestParam(required = false) String phone,
                                 @RequestParam(required = false) String oldpwd,
                                 @RequestParam(required = false) String newpwd){
        ResponseDto result=ResponseDto.build(000,"操作成功");
        String sso_key=HttpKit.getRequest().getHeader("Authorization");
        if(StringUtil.isEmpty(sso_key)){
               throw  new BusinessException(BizExceptionEnum.NO_THIS_USER);
        }
        if(StringUtil.isEmpty(phone)||StringUtil.isEmpty(oldpwd)||StringUtil.isEmpty(newpwd)
                ||StringUtil.isEmpty(sso_key)){
               throw new BusinessException(BizExceptionEnum.REQUEST_NULL);
        }
        User user= (User) redisTemplate.opsForValue().get(sso_key);
        if(user==null){
            return ResponseDto.build(AppConstant.Code.NOT_LOGIN,AppConstant.Msg.NOT_LOGIN);
        }
        else {
            if(!user.getPassword().equals(oldpwd)){
                return ResponseDto.build(AppConstant.Code.FAIL,"原密码错误");
            }
            else {
                user.setPassword(newpwd);
                userApi.update(user);
                //key 存入redis 并且返回响应
                redisTemplate.delete(sso_key);
                //新key
                String sso_user_key= StringUtil.getUUID();
                redisTemplate.opsForValue().set(sso_user_key,user,30,TimeUnit.MINUTES);
                HttpKit.addCookie(HttpKit.getResponse(),"sso_key",sso_user_key,3600);
                result.setData(sso_user_key);
            }
        }
            return result;
    }

    @ApiOperation(value = "手机验证码密码登录", notes="未注册账号会自动注册",
            produces = "application/json; charset=utf-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
            @ApiImplicitParam(name = "code", value = "短信验证码",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
    })
    @RequestMapping(value = "codeLogin",method = RequestMethod.GET)
    public ResponseDto codeLogin(String phone, String code) {
        ResponseDto result =ResponseDto.build(BizExceptionEnum.SUCCESSFUL_OPERATION);
            if (StringUtil.isEmpty(phone)) {
                result.setCode(AppConstant.Code.FAIL);
                result.setMesg("电话号码不能为空");
                return result;
            }
            if (StringUtil.isEmpty(code)) {
                result.setCode(AppConstant.Code.FAIL);
                result.setMesg("验证码不能为空");
                return result;
            }
            String redisCodeKey = BusinessConstant.p1RedisPrex.SMS_PHONE_PRE +phone;
            String redisValidateCode = (String) redisTemplate.opsForValue().get(redisCodeKey);
          //  log.info("redis中获取验证码为："+redisValidateCode+"用户发送code为："+code);
            if (!code.equals(redisValidateCode)) {
                result.setCode(AppConstant.Code.FAIL);
                result.setMesg("验证码不匹配");
                return result;
            }

            UserQuery userQuery=new UserQuery();
            userQuery.setPhone(phone);
            User user=userApi.selectByQuery(userQuery);
            if(user!=null){


            }else{//注册
                User registerUser=new User();
                registerUser.setPhone(phone);
                userApi.insert(registerUser);
                user=registerUser;
                //新的六位密码
             String newPwd=   String.valueOf((Math.random()*9+1)*100000);
                 //发送短信
            }
           String sso_user_key= StringUtil.getUUID();
           redisTemplate.opsForValue().set(sso_user_key,user,30,TimeUnit.MINUTES);
           HttpKit.addCookie(HttpKit.getResponse(),"sso_key",sso_user_key,3600);
           result.setData(sso_user_key);
        return result;
    }


    @ApiOperation(value = "忘记密码", notes="通过手机验证码重置密码",
            produces = "application/json; charset=utf-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
            @ApiImplicitParam(name = "code", value = "短信验证码",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
            @ApiImplicitParam(name = "pwd", value = "新设置密码",
                    dataType = "int", paramType = "query", defaultValue="",required = true)
    })
    @RequestMapping(value="resetPwd",method = RequestMethod.POST)
    @LoginValidate
    public ResponseDto resetPwd(
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String pwd
    ) {
        ResponseDto result=new ResponseDto(AppConstant.Code.SUCCESS,AppConstant.Msg.SUCCESS,null);
            if (StringUtil.isEmpty(phone)) {
                result.setCode(AppConstant.Code.FAIL);
                result.setMesg("电话号码不能为空");
                return result;
            }
            if (StringUtil.isEmpty(code)) {
                result.setCode(AppConstant.Code.FAIL);
                result.setMesg("验证码不能为空");
                return result;
            }
            String redisCodeKey = BusinessConstant.p1RedisPrex.SMS_CODE_PRE  + phone;
            String redisValidateCode = (String) redisTemplate.opsForValue().get(redisCodeKey);
            if (!code.equals(redisValidateCode)) {
                result.setCode(AppConstant.Code.FAIL);
                result.setMesg("验证码不匹配");
                return result;
            }
            UserQuery userQuery=new UserQuery();
            userQuery.setPhone(phone);
            userApi.update(userQuery);
        return result;
    }

    /**
     * 退出登录
     */
    @ApiOperation(value = "登出系统", notes="清空cookie session",
            produces = "application/json; charset=utf-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token秘钥",
                    dataType = "int", paramType = "query", defaultValue="",required = true),
    })
    @RequestMapping(value="loginOut",method = RequestMethod.POST)
    @LoginValidate
    public ResponseDto loginOut() {
        ResponseDto result=new ResponseDto(AppConstant.Code.SUCCESS,AppConstant.Msg.SUCCESS,null);
        String sso_key=HttpKit.getRequest().getHeader("Authorization");
        if(StringUtil.isEmpty(sso_key)){
            throw  new BusinessException(BizExceptionEnum.NO_THIS_USER);
        }
        redisTemplate.delete(sso_key);
        return result;
    }
}
